package com.mantru.iotpot.setting;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.R;

public class CleaningPipeActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout back;
    private TextView title;
    private TextView date;
    private Button wash;
//    private String name = "[生抽]、[耗油]、[盐水]";
    private String name = "";
    private ApplicationClass ac;
    private int back_star = 1; // 1：未开始清洗、2：清洗中、3：清洗完成
    private TextView time;
    private int secound = 120; // 倒计时总时间，单位：秒
    private CountDownTimer countDownTimer;
    private AlertDialog dialog;
    private long remainingMillis; // 用于存储暂停时剩余的时间（毫秒）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cleaning_pipe);
        ac = (ApplicationClass) getApplication(); // 初始化 ApplicationClass
        initialization(); // 初始化控件
        name = ac.GetSQLData_Cleaning_Nozzle_GetNameList();
        date.setText("请先将 " + name + " 的料管\n" + "放在一桶/盆清水中，点击下方清洗按钮即可完成自动清洗");
    }

    // 初始化控件
    private void initialization() {
        back = findViewById(R.id.cleaning_pipe_back);
        title = findViewById(R.id.cleaning_pipe_title);
        date = findViewById(R.id.cleaning_pipe_date);
        time = findViewById(R.id.cleaning_pipe_time);
        wash = findViewById(R.id.cleaning_pipe_wash);
        wash.setOnClickListener(this);
        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.cleaning_pipe_wash) { // 点击开始清洗按钮
            back_star = 2;
            ac.GetSQLData_Cleaning_Nozzle_Start();
            wash.setVisibility(View.GONE);
            time.setVisibility(View.VISIBLE);
            startCountDownTimer(); // 启动倒计时
        } else if (v.getId() == R.id.cleaning_pipe_back) { // 点击返回按钮
            if (back_star == 1) { // 未开始清洗
                finish();
            } else if (back_star == 2) { // 开始清洗后
                pauseCountDownTimer(); // 暂停倒计时
                showDialog();
            }
        }
    }

    // 显示弹窗
    private void showDialog() {
        if (isFinishing() || isDestroyed()) {
            return; // 如果 Activity 正在销毁或已经销毁，直接返回
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.cleaning_pipe_dialog, null);
        TextView dialog_title = dialogView.findViewById(R.id.cleaning_pipe_dialog_title);
        Button cancle = dialogView.findViewById(R.id.cleaning_pipe_dialog_cancle);
        Button confirm = dialogView.findViewById(R.id.cleaning_pipe_dialog_confirm);
        Button dialog_finish = dialogView.findViewById(R.id.cleaning_pipe_dialog_back);
        builder.setView(dialogView);
        dialog = builder.create();
        if (back_star == 3) { // 清洗完成
            dialog_title.setText("清洗料管已完成");
            cancle.setVisibility(View.GONE);
            confirm.setVisibility(View.GONE);
            dialog_finish.setVisibility(View.VISIBLE);
            dialog_finish.setOnClickListener(v -> {
                dialog.dismiss();
                finish();
            });
        } else {//清洗中
            cancle.setOnClickListener(v -> { // 点击取消按钮（恢复倒计时）
                dialog.dismiss();
                resumeCountDownTimer(); // 恢复倒计时
            });
            confirm.setOnClickListener(v -> { // 点击确认按钮（取消清洗）
                ac.GetSQLData_Cleaning_Nozzle_Stop();
                dialog.dismiss();
                finish();
            });
        }
        dialog.show();
        // 关键代码：设置窗口背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 关键代码：设置点击外部不可取消
        dialog.setCanceledOnTouchOutside(false);
    }

    // 启动倒计时方法
    private void startCountDownTimer() {
        remainingMillis = secound * 1000; // 初始化剩余时间为总时间
        countDownTimer = new CountDownTimer(remainingMillis, 1000) { // 时间，每秒更新一次
            @Override
            public void onTick(long millisUntilFinished) {
                // 更新显示的秒数
                remainingMillis = millisUntilFinished; // 记录剩余时间
                int seconds = (int) (millisUntilFinished / 1000);
                Log.d("CleaningPipeActivity", "seconds: " + seconds);
                time.setText(seconds + "秒");
            }
            @Override
            public void onFinish() {
                if (isFinishing() || isDestroyed()) {
                    return; // 确保 Activity 未销毁
                }
                back_star = 3;
                runOnUiThread(() -> {
                    if (!isFinishing() && !isDestroyed()) {
                        showDialog(); // 在主线程安全显示对话框
                    }
                });
                ac.GetSQLData_Cleaning_Nozzle_Stop();
            }
        }.start();
    }

    // 暂停倒计时
    private void pauseCountDownTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel(); // 取消当前计时器
            Log.d("CleaningPipeActivity", "暂停倒计时，剩余时间: " + remainingMillis);
        }
    }

    // 恢复倒计时
    private void resumeCountDownTimer() {
        if (remainingMillis > 0) {
            countDownTimer = new CountDownTimer(remainingMillis, 1000) { // 使用剩余时间恢复倒计时
                @Override
                public void onTick(long millisUntilFinished) {
                    remainingMillis = millisUntilFinished; // 更新剩余时间
                    int seconds = (int) (millisUntilFinished / 1000);
                    Log.d("CleaningPipeActivity", "恢复倒计时，剩余秒数: " + seconds);
                    time.setText(seconds + "秒");
                }
                @Override
                public void onFinish() {
                    if (isFinishing() || isDestroyed()) {
                        return; // 确保 Activity 未销毁
                    }
                    back_star = 3;
                    runOnUiThread(() -> {
                        if (!isFinishing() && !isDestroyed()) {
                            showDialog(); // 在主线程安全显示对话框
                        }
                    });
                    ac.GetSQLData_Cleaning_Nozzle_Stop();
                }
            }.start();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel(); // 取消计时器
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss(); // 关闭对话框
        }
    }
}